<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue.js</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href="style.css" />
    <script src="vue.js"></script>
  </head>
  <body onload="draw()">
    <div id="vue-app"></div>
    <canvas id="canvas" width="800" height="600">
      你这浏览器不支持这玩意啊
    </canvas>
    <script src="app.js"></script>
    <script>
      function draw() {
        // 让vscode可以显示canvas智能提示
        /** @type {HTMLCanvasElement} */
        const canvas = document.getElementById('canvas');
        if (canvas.getContext) {
          const ctx = canvas.getContext('2d');
          /**
           * 用面向对象方式写
           */
          // Rectangle类
          function Rect(x, y, width, height, color, speed) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.color = color;
            this.speed = speed;
            // 绘制方法
            Rect.prototype.draw = function () {
              ctx.beginPath();
              ctx.fillStyle = this.color;
              ctx.fillRect(this.x, this.y, this.width, this.height);
              ctx.closePath();
            };
            //移动
            Rect.prototype.move = function () {
              this.x += this.speed;
              if (this.x >= canvas.width - this.width) {
                this.speed *= -1;
              } else if (this.x < 0) {
                this.speed *= -1;
              }
              // this.y += this.speed;
              // if (this.x >= canvas.height - this.height) {
              //   this.speed *= -1;
              // } else if (this.x < 0) {
              //   this.speed *= -1;
              // }
            };
          }
          const rect1 = new Rect(0, 100, 100, 100, 'red', 4);
          const rect2 = new Rect(700, 100, 100, 100, 'blue', -2);
          rect1.draw();
          rect2.draw();
          function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            rect1.move();
            rect2.move();
            rect1.draw();
            rect2.draw();
            //判断是否碰撞
            if (isRectHit(rect1, rect2)) {
              rect1.speed *= -1;
              rect2.speed *= -1;
            }
            //递归调用
            window.requestAnimationFrame(animate);
          }
          function isRectHit(rect1, rect2) {
            // 获取矩形的最小x和最大x
            const min1 = rect1.x;
            const min2 = rect2.x;
            const max1 = rect1.x + rect1.width;
            const max2 = rect2.x + rect2.width;
            const min3 = Math.max(min1, min2);
            const max3 = Math.min(max1, max2);
            if (min3 < max3) {
              return true;
            } else {
              return false;
            }
          }
          animate();
        }
      }
    </script>
  </body>
</html>
